<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/dao/dbConnection.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/update.php';

class UpdateDao {
	private $_db;

	public function __construct() {
		$this->_db = new DbConnection();
		$this->_db->connect();
	}

	/**
	 *
	 * Add an update to the database
	 * @param $update: an instance of UpdateModel object
	 */
	public function addUpdate($update) {
		$query = sprintf("CALL sp_AddUpdate('%u', '%u', '%u', '%u', '%s', '%s')",
		$update->getUserId(), $update->getUpdateType(), $update->getIndicteeId(), $update->getModifiedDate(), $update->getLink(), $update->getName());

		$result = $this->_db->executeQuery($query);

		if (!$result) {
			echo 'Could not run query: ' . ' ' . mysql_error();
			return 0;
		}

		$row = mysql_affected_rows();

		return ($row != 0);
	}

	public function getUpdatesOfUser($userID) {
		global $ubi;
		$updates = array();
		$query = sprintf("SELECT * FROM updates WHERE UserId = '%d' ORDER BY ModifiedDate DESC LIMIT %d ", 
			$userID, $ubi['SITE']['NUMBER_OWNER_UPDATE']);
		
		$result = $this->_db->executeQuery($query);

		if ($result) {
			while ($row = mysql_fetch_assoc($result)) {
				$updates[] = $this->setUpdateByAssoc($row);
			}
			
			return $updates;
		}
	}
	
	public function getUpdatesOfFriends($userID) {
		global $ubi;
		$updates = array();
		
		$query = sprintf("
			SELECT * FROM updates WHERE updates.UserId in
           		(select FriendId from friends
           		where UserId = '%d')
     		ORDER BY ModifiedDate DESC
     		LIMIT %d", $userID, $ubi['SITE']['NUMBER_FRIENDS_UPDATE']);
		
		$result = $this->_db->executeQuery($query);
		
		if ($result) {
			while ($row = mysql_fetch_assoc($result)) {
				$updates[] = $this->setUpdateByAssoc($row);
			}
			
			return $updates;	
		}
	}
	
	private function setUpdateByAssoc($row) {
		$update = new UpdateModel();
			
		$update->setIndicteeID($row['IndicteeId']);
		$update->setLink($row['Link']);
		$update->setModifiedDate($row['ModifiedDate']);
		$update->setName($row['Name']);
		$update->setUpdateType($row['UpdateType']);
		$update->setUserID($row['UserId']);
		
		return $update;
	}
}
?>